import { Component, OnInit } from '@angular/core';
import { ApesMessageService } from '@shared/apes/message';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { PurchaseService } from '../purchase.service';
import { ApiService } from '@core/services/http/api.service';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
import { format } from 'date-fns';

@Component({
  selector: 'integrated-panel',
  templateUrl: './integrated-panel.component.html',
  styleUrls: ['../purchase-report-form.scss'],
})
export class IntegratedPanelComponent implements OnInit {
  /** 按钮相关 **/
  buttonBar = [
    { hide: true, style: 'default', label: '查询', id: 'action_query' },
    { hide: true, style: 'default', label: '导出', id: 'action_pdf' },
  ];
  title = '';
  ctx = { model: {} };

  timeList: any = [];                 // 审核日期
  supplier: any;
  supplierID: string;
  supplierName: string;

  but = [
    { value: 7 },
    { value: 30 },
    { value: 90 },
  ];

  pdata = { 'START_RQ': '', 'END_RQ': '', 'GYSID': '' };
  chart: any;
  newData: any[] = [];
  brandData: any[] = [];
  RKFXSL: number;

  pieData = [
    {
      title: '入库时效分析',
      label: '总入库数量',
      key: undefined,
      hasLegend: true,
      data: { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryRKSX', 'pdata': this.pdata },
      pieData: [],
    },
    {
      title: '品牌件报价分析',
      hasLegend: false,
      data: { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryPPJBJ', 'pdata': this.pdata },
      pieData: [],
    },
    {
      title: '返厂时效',
      label: '总返厂数量',
      key: undefined,
      labelTwo: '返厂率',
      keyTwo: undefined,
      hasLegend: true,
      data: { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryFCFX', 'pdata': this.pdata },
      pieData: [],
    },
    {
      title: '报价时效分析',
      label: '超时率',
      key: undefined,
      labelTwo: '未报价率',
      keyTwo: undefined,
      data: { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryGYSBJSX', 'pdata': this.pdata },
      pieData: [],
    },
  ];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private pa: PurchaseService) {
  }

  ngOnInit() {
    this.initialization();
  }

  // 初始化
  initialization() {
    // 默认 请求 当天 数据
    this.timeList = this.pa.dayChang(0);
    this.pa.getSupplierData().then(value => {
      this.supplier = value;
    });

  }

  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.queryData();
      } else if (data.id === 'action_pdf') {
        this.action_pdf();
      }
    }
  }

  // 导出数据
  action_pdf() {
    const data = document.getElementById('pdf');
    html2canvas(data).then(canvas => {
      // Few necessary setting options
      const imgWidth = 208;
      const pageHeight = 295;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      const heightLeft = imgHeight;

      const contentDataURL = canvas.toDataURL('image/png');
      const pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
      const position = 0;
      pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      pdf.save('供应商综合分析面板.pdf'); // Generated PDF
    });
  }

  queryData() {
    if (JSON.stringify(this.timeList) !== '[]') {
      this.timeList[0] = format(this.timeList[0], 'YYYY-MM-DD');
      this.timeList[1] = format(this.timeList[1], 'YYYY-MM-DD');
    }
    for (let item of this.supplier) {
      if (item.GYSID === this.supplierID) {
        this.supplierName = item.GYSMC;
      }
    }
    if (JSON.stringify(this.timeList) !== '[]' && this.supplierID !== undefined && this.supplierID !== null) {
      this.RKFXSL = null;
      for (let item of this.pieData) {
        item.data.pdata.START_RQ = this.timeList[0];
        item.data.pdata.END_RQ = this.timeList[1];
        item.data.pdata.GYSID = this.supplierID;
        item.pieData = [];
        this.pa.getPie(item.data, item.title).then(value => {
          if (item.title === '入库时效分析') {
            if (JSON.stringify(value) !== '[]') {
              item.pieData[0] = value[0];
              if(JSON.stringify(item.pieData) !== '[]') {
                let pieData: any[];
                for (let list of item.pieData) {
                  item.key = list['RKZSL'] + '个';
                  pieData = [
                    { x: '1小时内入库', y: list['ONE_HOURS'], RKZSL: list['RKZSL'] },
                    { x: '1-2小时内入库', y: list['ONE_TWO_HOURS'] },
                    { x: '2-3小时内入库', y: list['TWO_TO_THREE_HOURS'] },
                    { x: '3-4小时内入库', y: list['THREE_TO_FOUR_HOURS'] },
                    { x: '超4小时入库', y: list['MORE_FOUR_HOURS'] },
                  ];
                }
                item.pieData = pieData;
              }
            }
          }
          else if (item.title === '品牌件报价分析') {
            item.pieData['array'] = value;
            if(JSON.stringify(item.pieData['array']) !== '[]') {
              //  饼图数据处理
              let pieData: any[] = item.pieData['array'].map(list => {
                if (list['TYPE'] !== '合计' && list['TYPE'] !== undefined) {
                  return { x: list.TYPE, y: list.BJS };
                }
              });
              //  表格数据处理
              this.brandData = item.pieData['array'].map(list => {
                if (list['TYPE'] !== undefined) {
                  return list;
                }
              });
              // 数组清除undefined
              this.brandData = this.brandData.filter( res => {
                return res !== undefined;
              });
              pieData = pieData.filter( res => {
                return res !== undefined;
              });
              item.pieData = pieData;
            }
          }
          else if (item.title === '返厂时效') {
            item.pieData['array'] = value;
            if(JSON.stringify(item.pieData['array']) !== '[]') {
              item.key = item.pieData['array'][0]['FCZSL'] + '个';
              item.keyTwo = (item.pieData['array'][0]['FCL'] * 100 ).toFixed(2) + '%';
              let pieData: any[] = item.pieData['array'].map(list => {
                return { ...list, x: list.FCTHYYMC, y: list.FCSL };
              });
              item.pieData = pieData;
            }
          }
          else if (item.title === '报价时效分析') {
            item.pieData['array'] = value;
            item.pieData = item.pieData['array'];
            if(JSON.stringify(item.pieData) !== '[]') {
              item.key = ((item.pieData[item.pieData.length - 1]['CSSL'] / item.pieData[item.pieData.length - 1]['WCBJ']) * 10 ).toFixed(2) + '%';
              item.keyTwo = ((item.pieData[item.pieData.length - 1]['WWCBJ'] / item.pieData[item.pieData.length - 1]['TSBJS']) * 10 ).toFixed(2) + '%';
            }
          }
        });
      }
      this.chartLine();
    } else {
      this.msg.error('日期、供应商不能为空！');
    }
  }

  _submit($event) {
    this.timeList = this.pa.dayChang($event);
  }

  chartLine() {
    const list = { 'interfaceMethod': 'ipmSupplierAnalysisReportService.qryGYSBJSX_ZXT', 'pdata': this.pdata };
    this.apiService.post('report.interface', { 'body': JSON.stringify(list) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            const data = JSON.parse(result.obj);
            this.newData = [];
            const newList: any[] = [];
            for (let item of data) {
              item['KSRQ_SJ'] = format(item['KSRQ_SJ'], 'YYYY-MM-DD');
              const array: any[] = [];
              const cloneArr = [{}, {}, {}];
              array.push(item);
              for (let arr of array) {
                cloneArr[0] = { date: arr['KSRQ_SJ'], type: 'wwcbj', value: arr['WWCBJ'] };
                cloneArr[1] = { date: arr['KSRQ_SJ'], type: 'cssl', value: arr['CSSL'] };
                cloneArr[2] = { date: arr['KSRQ_SJ'], type: 'wcbj', value: arr['WCBJ'] };
              }
              newList.push(cloneArr);
            }
            for (let item of newList) {
              for (let list of item) {
                this.newData.push(list);
              }
            }
            this.barChart(this.newData);
          }
        }
      });


  }

  barChart(data) {
    if (this.chart) {
      this.chart.destroy();
      this.chart = null;
    }

    this.chart = new G2.Chart({
      container: 'pieNode',
      forceFit: true,
      height: 340,
      padding: [100, 20, 30, 45], // 上右下左
    });
    this.chart.source(data);
    this.chart.tooltip({
      useHtml: true,
      follow: false,
      crosshairs: 'y',
      htmlContent: function htmlContent(title, items) {
        let alias = {
          wcbj: '完成报价',
          cssl: '超时台次',
          wwcbj: '未报价',
        };
        let html = '<div class="custom-tooltip">';
        for (let i in items) {
          const item = items[i];
          const color = item.color;
          const name = alias[item.name];
          const value = item.value;
          const domHead = '<div class="custom-tooltip-item" style="border-left-color:' + color + '">';
          const domName = '<div class="custom-tooltip-item-name">' + name + '</div>';
          const domValue = '<div class="custom-tooltip-item-value">' + value + '</div>';
          const domTail = '</div>';
          html += domHead + domName + domValue + domTail;
        }
        return html + '</div>';
      },
    });
    this.chart.axis('date', {
      label: {
        textStyle: {
          fill: '#aaaaaa',
        },
      },
    });
    this.chart.axis('value', {
      label: {
        textStyle: {
          fill: '#aaaaaa',
        },
        formatter: function formatter(text) {
          return text.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        },
      },
    });
    this.chart.legend(false);
    this.chart.line().position('date*value').color('type');
    this.chart.render();
    let wi = document.querySelector('#pieNode')['clientWidth'];
    this.chart.showTooltip({
      x: wi,
      y: 100,
    });
  }

}
